package com.huo.common;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Description: 创建线程池
 * </p>
 * 
 * @author Huoyan
 * @version 1.0
 *          <p>
 *          Copyright 2011
 *          </p>
 */

public class ThreadPool {

	/**
	 * 线程池默认线程数量
	 */
	private static final int DEFAULT_POOL_SIZE = 10;
	
	/**
	 * 线程池最大线程数量
	 */
	private static final int MAXIMUM_POOL_SIZE = 500;
	
	/**
	 * 线程池中线程数多于默认线程数时，所允许的多出线程的空闲时间。
	 */
	private static final long KEEP_ALIVE_TIME = 60000L;
	
	/**
	 * 线程池实例
	 */
	private ExecutorService execService = null;
	
	/**
	 * 静态内部类
	 * @author Huoyan
	 *
	 */
	private static class InnerThreadPool {
		private final static ThreadPool tp = new ThreadPool();
	}

	public static ThreadPool getInstance() {
		return InnerThreadPool.tp;
	}
	
	/**
	 * 执行线程任务
	 * @param command
	 */
	public void execute(Runnable command){
		execService.execute(command);
	}
	
	public ExecutorService getExecutorService(){
		return execService;
	}
	
	/**
	 * 关闭线程池
	 */
	public void shutdown(){
		execService.shutdown();
	}
	
	private ThreadPool() {
		//创建线程池
		execService = new ThreadPoolExecutor(
				DEFAULT_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME,
				TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
	}
}
